﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GalaSoft.MvvmLight;
using wp8nop.Common;
using System.Diagnostics;
using GalaSoft.MvvmLight.Ioc;
using wp8nop.Model;
using System.Globalization;
using System.Net.Http;
using Microsoft.Phone.Tasks;

namespace wp8nop
{
    public partial class ConfermaOrdine : PhoneApplicationPage
    {
        public ConfermaOrdine()
        {
            InitializeComponent();
            grNumTelefono.Visibility = System.Windows.Visibility.Collapsed;
            _dataService = SimpleIoc.Default.GetInstance<IDataService>();

            this.Loaded += ConfermaOrdine_Loaded;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (_dataService.Carrello.Count == 0)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                return;
            }
            btConferma.Visibility = System.Windows.Visibility.Visible;
            esito.Text = "";
            tbTel.Text = "";
            totOrdine.Text = "Totale ordine: " + string.Format("{0:F2}€", _dataService.GetTotaleCarrello() + _dataService.GetSpedizioni());
            if (App.TipoPagamento == "contrassegno")
                grNumTelefono.Visibility = System.Windows.Visibility.Visible;
            else
                grNumTelefono.Visibility = System.Windows.Visibility.Collapsed;

            btOk.Visibility = System.Windows.Visibility.Collapsed;
            base.OnNavigatedTo(e);
        }
        IDataService _dataService;
        void ConfermaOrdine_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void ConfermaOrdine_Click(object sender, RoutedEventArgs e)
        {
            if (App.TipoPagamento == "contrassegno" && tbTel.Text.Trim() == "")
            {
                Toast.SendToast("Inserisci il numero di telefono");
                return;
            }


            nopService.NopServiceClient client = new nopService.NopServiceClient();
            client.ConfirmOrderCompleted += client_ConfirmOrderCompleted;
            progress.IsIndeterminate = true;

            List<nopService.productscart> cart = new List<nopService.productscart>();

            foreach (var prod in _dataService.Carrello)
            {
                nopService.productscart item = new nopService.productscart();
                item.idcustomer = App.IDUtente;
                item.pag = App.TipoPagamento;
                item.tel = tbTel.Text;
                item.user = App.Email;
                item.pwd = App.Password;
                item.qty = prod.Quantita;
                item.prodid = int.Parse(prod.Model.id);
                cart.Add(item);
            }

            client.ConfirmOrderAsync(cart);
          
        }

        void client_ConfirmOrderCompleted(object sender, nopService.ConfirmOrderCompletedEventArgs e)
        {
            progress.IsIndeterminate = false;
            if (e.Error != null)
                Toast.SendToast("Si è verificato un errroe di comunicazione con i nostri server, provare più tardi");

            else
            {
                Debug.WriteLine("Result: " + e.Result.ToString());
                if (e.Result.esito == 0)
                {
                    btConferma.Visibility = System.Windows.Visibility.Collapsed;
                    if (App.TipoPagamento == "bonifico")
                    {
                        esito.Text = "Il tuo ordine è stato confermato. Riceverai via mail gli estremi per il bonifico";
                        Toast.SendToast("Ordine confermato");
                        btOk.Visibility = System.Windows.Visibility.Visible;
                        _dataService.Carrello.Clear();
                    }
                    else if (App.TipoPagamento == "contrassegno")
                    {
                        esito.Text = "Il tuo ordine è stato confermato.";
                        Toast.SendToast("Ordine confermato");
                        btOk.Visibility = System.Windows.Visibility.Visible;
                        _dataService.Carrello.Clear();
                    }
                    else if (App.TipoPagamento == "paypal" || App.TipoPagamento == "cartacredito")
                    {
                        esito.Text = "A breve sarai trasferito su paypal...";
                        Toast.SendToast("Trasferimento al server di pagamento in corso...");
                
                        PayWithPaypal(e.Result.idordine, _dataService.GetTotaleCarrello() + _dataService.GetSpedizioni());
                    }


                }
                else
                {
                    Toast.SendToast(e.Result.message);
                }
            }
        }

        private async void PayWithPaypal(int idordine, double totaleordine)
        {
            progress.IsIndeterminate = true;
            var values = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("USER", "## insert user here ###"),
                    new KeyValuePair<string, string>("PWD", "### insert pwd here ###"),
                    new KeyValuePair<string, string>("SIGNATURE", "### insert signature here ###"),             
                    new KeyValuePair<string, string>("METHOD", "SetExpressCheckout"),
                    new KeyValuePair<string, string>("VERSION", "78"),
                    new KeyValuePair<string, string>("PAYMENTREQUEST_0_PAYMENTACTION", "SALE"),
                    new KeyValuePair<string, string>("PAYMENTREQUEST_0_AMT", totaleordine.ToString("0.00", CultureInfo.InvariantCulture)),
                    new KeyValuePair<string, string>("PAYMENTREQUEST_0_CURRENCYCODE", "EUR"),
                    new KeyValuePair<string, string>("LOCALECODE", "IT"),
                    new KeyValuePair<string, string>("cancelUrl", "http://127.0.0.1/Pers/CheckOutNo.aspx"),
                    new KeyValuePair<string, string>("returnUrl", "http://127.0.0.1/Pers/CheckOutOk.aspx"),
                                          
                };
            if (App.TipoPagamento == "cartacredito")
            {
                values.Add(new KeyValuePair<string, string>("SOLUTIONTYPE", "Sole"));
                values.Add(new KeyValuePair<string, string>("LANDINGPAGE", "Billing"));
            }

            var httpClient = new HttpClient(new HttpClientHandler());
            HttpResponseMessage response = await httpClient.PostAsync("https://api-3t.paypal.com/nvp", new FormUrlEncodedContent(values));
            response.EnsureSuccessStatusCode();
            var responseString = await response.Content.ReadAsStringAsync();


            string lab = HttpUtility.UrlDecode(responseString);
            string token = "";
            string[] str = lab.Split('&');
            foreach (var el in str)
            {
                string[] tok = el.Split('=');
                if (tok[0] == "TOKEN")
                    token = tok[1];
            }

            progress.IsIndeterminate = false;
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout-mobile&useraction=commit&token=" + token, UriKind.Absolute);
            webBrowserTask.Show();
        }

        private void Ok_Click(object sender, RoutedEventArgs e)
        {
            while (this.NavigationService.BackStack.Any())
            {
                this.NavigationService.RemoveBackEntry();
            }

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

    }
}